/**
 * 请求外部api
 * options: {
 *  method: get、post 请求方式，默认get
 *  url: '' 接口地址
 *  data: {} 请求参数
 * }
 */

import { Injectable } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { lastValueFrom } from 'rxjs';

function parseParam(params: { [key: string]: any }) {
  return Object.keys(params)
    .map((key) => {
      return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
    })
    .join('&');
}

@Injectable()
export class httpClint {
  constructor(private http: HttpService) {}

  // 远程接口请求
  async originApi(options: any) {
    let checkResultObservable; // 远程接口响应数据
    if (options.method === 'post') {
      // POST
      checkResultObservable = this.http.post(options.url, options.data || {});
    } else {
      // GET
      let url = options.url;
      if (options.data) {
        // 序列化参数
        url += '?' + parseParam(options.data);
      }
      checkResultObservable = this.http.get(url);
    }
    // lastValueFrom处理Observable格式数据，转换为对象格式
    const checkResult: any = await lastValueFrom(checkResultObservable);
    return checkResult.data;
  }
}
